import * as actions from '../actions/subredditAction';

export const selectedSubreddit = (state = 'reactjs', action) => {
    switch(action.type) {
        case actions.SELECT_SUBREDDIT:
            return action.subreddit;
        default:
            return state;
    }
};

const initialState = { 
    isFetching: false, 
    didiInvalidate: false, 
    items: [] 
};
export const posts = (state = initialState, action) => {
    switch(action.type) {
        case actions.INVALIDATE_SUBREDDIT:
            return { ...state, didInvalidate: true };
        case actions.REQUEST_POSTS:
            return { 
                ...state, 
                isFetching: true, 
                didiInvalidate: false 
            };
        case actions.RECEIVE_POSTS:
            return {
                ...state,
                isFetching: false,
                didiInvalidate: false,
                items: action.posts,
                lastUpdated: action.receivedAt
            };
        default:
            return state;
    }
};

export const postsBySubreddit = (state = {}, action) => {
    switch(action.type) {
        case actions.INVALIDATE_SUBREDDIT:
        case actions.RECEIVE_POSTS:
        case actions.REQUEST_POSTS:
            return {
                ...state,
                [action.subreddit]: posts(state[action.subreddit], action)
            };
        default:
            return state;
    }
};

export default { postsBySubreddit, selectedSubreddit };